from rest_framework.decorators import action
from rest_framework.viewsets import ViewSet, ModelViewSet, ReadOnlyModelViewSet
from rest_framework import viewsets, mixins
from rest_framework.response import Response
from Drf_api.paginations import ProductPageNumberPagination
from product.models import Product
from Apis.serializers import ProductModelSerializer, ReviewModelSerializer
from django.core.management.commands import runserver
from django_filters.rest_framework import DjangoFilterBackend
class ProductViewset(ViewSet):

    # 商品列表
 
    def list(self, request):
        queryset = Product.objects.filter(is_active=True)
        serializer = ProductModelSerializer(queryset, many=True)
        return Response({"message": "success", "data":serializer.data})
    
    # 商品详情
 
    def retrieve(self, request, pk=None):
        try:
            products = Product.objects.get(pk=pk)
            serializer = ProductModelSerializer(products)
            return Response({"message": "success", "data": serializer.data})
        except Product.DoesNotExist:
            return Response({"message": "商品不存在！"}, status=404)

    # 商品创建
    def create(self, request):
        try:
            serializer = ProductModelSerializer(data=request.data)
            if serializer.is_valid(raise_exception=True):
                serializer.save()
                return Response({"message": "success", "data": serializer.data}, status=201)
        except Exception as e:
            return Response(serializer.errors, status=400)

    # 商品更新 全量更新 全部的字段都必须要传入
    def update(self, request, pk=None):
        try:
            products = Product.objects.get(pk=pk)
            serializer = ProductModelSerializer(products, data=request.data)
            if serializer.is_valid(raise_exception=True):
                serializer.save()
                return Response(serializer.data)
        except Product.DoesNotExist:
            return Response({"message": "商品不存在！"}, status=404)
    
    # 商品更新 部分更新(patch) 单个字段传入
    def partial_update(self, request, pk=None):
        try:
            products = Product.objects.get(pk=pk)
            serializer = ProductModelSerializer(products, data=request.data, partial=True)
            if serializer.is_valid(raise_exception=True):
                serializer.save()
                return Response(serializer.data)
        except Product.DoesNotExist:
            return Response({"message": "商品不存在！"}, status=404)

    # 商品删除
    def delete(self, request, pk=None):
        try:
            products = Product.objects.get(pk=pk)
            products.delete()
            return Response({"message": "success"}, status=204)
        except Product.DoesNotExist:
            return Response({"message": "商品不存在！"}, status=404)

# GenericViewSet 继承了 ViewSetMixin
class ProductGenriceViewset(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.RetrieveModelMixin, 
                            mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin):

     queryset = Product.objects.all()
     serializer_class = ProductModelSerializer

# 具备全部的增删改查
class ProductModelViewset(viewsets.ModelViewSet):
     queryset = Product.objects.all()
     serializer_class = ProductModelSerializer
     # 配置过滤器后端
     filter_backends = [DjangoFilterBackend]
     # 配置过滤的字段
     filterset_fields = ['product_name', 'price']
    # 分页
     pagination_class = ProductPageNumberPagination
    # 重写删除方法
    #  def perform_destroy(self, instance):
    #     instance.is_active = False
    #     instance.save()

    # 默认的vieset 只提供标准的crud 方法
    # 如果需要额外的功能，就可以用@action添加
    # 通过@action 装饰器 自定义方法
     @action(methods=['GET'], detail=True, url_path="reviews")
     def review(self, request, pk=None):
        """获取产品的所有评论"""
        # 获取当前产品对象
        product = self.get_object()
        reviews = product.review_set.filter()
        serialize = ReviewModelSerializer(reviews, many=True)
        return Response({"message": "success","data": serialize.data})

# 只读视图
class ProductReadOnlyModelViewset(viewsets.ReadOnlyModelViewSet):
     queryset = Product.objects.all()
     serializer_class = ProductModelSerializer


